package com.verbetia.musictrends.web.auth;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.verbetia.musictrends.persistence.hsqldb.UserEntity;
import com.verbetia.musictrends.persistence.hsqldb.UsersPersMngr;

public class LoginUser extends HttpServlet{

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		UserEntity userProfile = null;
		String username = request.getParameter("user");
		String password = request.getParameter("pass");
		
		if (username==null || password==null)	
				return;		
		
		UsersPersMngr users = new UsersPersMngr();
		int userid=UsersPersMngr.USER_NOT_EXSIST;
		
		try {
			userid = users.authenticateUser(username, password);
		} catch (SQLException e)
		{
			System.out.println(e);			
		}
			
		System.out.println(userid);
		
		if (userid==UsersPersMngr.USER_NOT_EXSIST)
			return;
		
		try {
			userProfile = users.getUserProfile(Integer.toString(userid));
		} catch (SQLException e)
		{
			System.out.println(e);
		}
		
		// put the user data in the session
		request.getSession().setAttribute("User", userProfile);
		request.getSession().setAttribute("username", userProfile.getUsername());
		
		System.out.println(userProfile.toString());
		
		response.sendRedirect("home.jsp");
		
				
		
	}

	protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
	}

}
